<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
          <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入商品价格"
          clearable
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="会员价" prop="memberPrice">
        <el-input
          v-model="queryParams.memberPrice"
          placeholder="请输入会员价"
          clearable
          @keyup.enter="handleQuery"
          style="width: 110px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable style="width: 80px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" /> 
        </el-select>
      </el-form-item> 
      <el-form-item label="删除状态" prop="isDeleted">
        <el-select v-model="queryParams.isDeleted" placeholder="请选择删除状态" clearable style="width: 100px">
            <el-option label="未删除" :value="0" />
            <el-option label="已删除" :value="1" /> 
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:goods:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="分类" align="center">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brandId" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="会员价" align="center" prop="memberPrice" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span>{{ scope.row.status === 1 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="规格" align="center" prop="goodsSpec" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!-- 优化后的标签显示列 -->
      <el-table-column label="标签" align="center">
        <template #default="scope">
          <div class="tag-container">
            <div 
              class="tag-item" 
              v-for="tag in getRowTags(scope.row)" 
              :key="tag.id"
            >
              {{ tag.name }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="operatorName" />
      <el-table-column label="逻辑删除" align="center" prop="isDeleted">
        <template #default="scope">
           <span>{{ scope.row.isDeleted === 1 ? '已删除' : '未删除' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:goods:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:goods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品分类">
            <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择商品品牌">
            <el-option v-for="brand in brandList" :key="brand.id" :label="brand.name" :value="brand.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品售价" />
        </el-form-item>
        <el-form-item label="会员价" prop="memberPrice">
          <el-input v-model="form.memberPrice" placeholder="请输入会员价格，为空时使用商品售价" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品规格" prop="goodsSpec">
          <el-input v-model="form.goodsSpec" placeholder="请输入商品规格信息，JSON格式存储" />
        </el-form-item>
        <el-form-item label="商品主图" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <!-- 标签选择按钮组 -->
        <el-form-item label="商品标签" prop="tags">
          <div class="tag-container">
            <div 
              v-for="tag in availableTags" 
              :key="tag.id"
              class="tag-item"
              :class="{ 'tag-selected': isTagSelected(tag.id) }"
              @click="toggleTag(tag.id)"
            >
              {{ tag.name }}
            </div>
          </div>
        </el-form-item>
      </el-form>
       <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
     </el-dialog>
   </div>
</template>

<script setup name="Goods">
import { listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/system/goods"
import { listCategory } from "@/api/system/category"
import useUserStore from '@/store/modules/user'
const userStore = useUserStore();

const { proxy } = getCurrentInstance()
const goodsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 分类和品牌列表
const categoryList = ref([])
const brandList = ref([
  { id: 1, name: '测试品牌' }
])

// 标签相关数据（过滤无效标签）
const availableTags = ref([
  { id: 1, name: '新品' },
  { id: 2, name: '热卖' },
  { id: 3, name: '促销' },
  { id: 4, name: '限时' },
  { id: 5, name: '爆款' },
  { id: 6, name: '折扣' }
].filter(tag => tag && tag.id && tag.name)) // 确保标签数据有效性

const selectedTagIds = ref([])

const data = reactive({
  form: {
    operatorName: userStore.nickName
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    categoryId: null,
    brandId: null,
    price: null,
    memberPrice: null,
    status: 1,
    description: null,
    goodsSpec: null,
    image: null,
    tags: null,
    operatorName: null,
    isDeleted: 0,
  },
  rules: {
    name: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "商品分类不能为空", trigger: "change" }
    ],
    price: [
      { required: true, message: "商品售价不能为空", trigger: "blur" },
      { validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('价格不能为负数'))
        } else {
          callback()
        }
      }, trigger: "blur" }
    ],
    status: [
      { required: true, message: "商品状态不能为空", trigger: "change" }
    ],
    tags: [
      { required: true, message: "请至少选择一个标签", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 监听表单标签变化，同步选中状态
watch(() => form.value.tags, (newVal) => {
  if (newVal) {
    selectedTagIds.value = newVal.split(',').map(Number).filter(id => id)
  } else {
    selectedTagIds.value = []
  }
}, { immediate: true })

/** 查询商品列表 */
function getList() {
  loading.value = true
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error => {
    loading.value = false
    proxy.$modal.msgError('获取数据失败：' + (error.msg || error.message))
  })
}

/** 加载所有分类 */
function loadAllCategories() {
  listCategory({ pageNum: 1, pageSize: 1000, isDeleted: 0 }).then(response => {
    categoryList.value = response.rows || []
  }).catch(error => {
    proxy.$modal.msgError('加载分类失败：' + (error.msg || error.message))
  })
}

/** 根据分类ID获取分类名称 */
function getCategoryName(categoryId) {
  if (!categoryId) return '未分类'
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.name : '未知分类'
}

/** 计算属性：根据行数据筛选需要显示的标签 */
function getRowTags(row) {
  if (!row.tags) return [] // 没有标签数据时返回空数组
  const rowTagIds = row.tags.split(',').map(Number) // 解析行数据中的标签ID
  // 筛选出匹配的标签
  return availableTags.value.filter(tag => rowTagIds.includes(tag.id))
}

/** 标签选择切换 */
function toggleTag(tagId) {
  const index = selectedTagIds.value.indexOf(tagId)
  if (index > -1) {
    // 取消选中
    selectedTagIds.value.splice(index, 1)
  } else {
    // 选中
    selectedTagIds.value.push(tagId)
  }
  // 同步到表单（用逗号分隔ID）
  form.value.tags = selectedTagIds.value.join(',')
}

/** 判断标签是否选中 */
function isTagSelected(tagId) {
  return selectedTagIds.value.includes(tagId)
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    categoryId: null,
    brandId: null,
    price: null,
    memberPrice: null,
    status: 1,
    description: null,
    goodsSpec: null,
    image: null,
    tags: null,
    operatorName: userStore.nickName,
    isDeleted: 0,
    createTime: null,
    updateTime: null
  }
  selectedTagIds.value = []
  proxy.resetForm("goodsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row ? row.id : (ids.value[0] || null)
  if (!_id) return
  getGoods(_id).then(response => {
    form.value = response.data
    // 初始化标签选中状态
    if (form.value.tags) {
      selectedTagIds.value = form.value.tags.split(',').map(Number).filter(id => id)
    }
    open.value = true
    title.value = "修改商品"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsRef"].validate(valid => {
    if (valid) {
      form.value.operatorName = userStore.nickName;
      if (form.value.id != null) {
        updateGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          proxy.$modal.msgError('修改失败：' + (error.msg || error.message))
        })
      } else {
        addGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(error => {
          proxy.$modal.msgError('新增失败：' + (error.msg || error.message))
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idsToDelete = row ? [row.id] : ids.value
  if (idsToDelete.length === 0) {
    proxy.$modal.msgWarning("请选择需要删除的数据")
    return
  }
  
  const idText = idsToDelete.join(',')
  proxy.$modal.confirm(`是否确认删除商品编号为"${idText}"的数据项？`).then(function() {
    return delGoods(idsToDelete)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`)
}

// 初始化
loadAllCategories()
getList()
</script>



<style scoped>
/* 标签样式 */
.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.tag-item {
  padding: 0px 12px;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #dcdfe6;
  font-size: 14px;
}

.tag-item:not(.tag-selected):hover {
  background-color: #f5f7fa;
}

.tag-selected {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}
</style>